import os
import json
import time
from typing import Dict, Any, List, Optional
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("deepresearch")

def save_report(report: str, topic: str, output_dir: Optional[str] = None) -> str:
    """Save the generated report to a file.
    
    Args:
        report: The text content of the report
        topic: The research topic
        output_dir: Directory to save the report (default: current directory)
        
    Returns:
        The path to the saved report file
    """
    # Create output directory if it doesn't exist
    if output_dir is None:
        output_dir = os.getcwd()
    
    os.makedirs(output_dir, exist_ok=True)
    
    # Create filename from topic
    safe_topic = "".join(c if c.isalnum() else "_" for c in topic)
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"{safe_topic}_{timestamp}.md"
    filepath = os.path.join(output_dir, filename)
    
    # Save report to file
    with open(filepath, "w", encoding="utf-8") as f:
        f.write(f"# Research Report: {topic}\n\n")
        f.write(report)
    
    logger.info(f"Report saved to {filepath}")
    return filepath

def save_research_data(research_data: Dict[str, Any], topic: str, output_dir: Optional[str] = None) -> str:
    """Save the raw research data to a JSON file.
    
    Args:
        research_data: Dictionary of research data
        topic: The research topic
        output_dir: Directory to save the data (default: current directory)
        
    Returns:
        The path to the saved data file
    """
    # Create output directory if it doesn't exist
    if output_dir is None:
        output_dir = os.getcwd()
    
    os.makedirs(output_dir, exist_ok=True)
    
    # Create filename from topic
    safe_topic = "".join(c if c.isalnum() else "_" for c in topic)
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"{safe_topic}_data_{timestamp}.json"
    filepath = os.path.join(output_dir, filename)
    
    # Save data to file
    with open(filepath, "w", encoding="utf-8") as f:
        json.dump(research_data, f, ensure_ascii=False, indent=2)
    
    logger.info(f"Research data saved to {filepath}")
    return filepath

def validate_api_keys() -> bool:
    """Validate that required API keys are set.
    
    Returns:
        True if all required keys are set, False otherwise
    """
    required_keys = {
        "TAVILY_API_KEY": os.environ.get("TAVILY_API_KEY")
    }
    
    missing_keys = [key for key, value in required_keys.items() if not value]
    
    if missing_keys:
        logger.error(f"Missing required API keys: {', '.join(missing_keys)}")
        return False
    
    return True

